package com.safety51.bi.controller;

import com.safety51.bi.entity.ChartConfig;
import com.safety51.bi.service.ChartConfigService;
import com.safety51.bi.service.DataQueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bi/debug")
@CrossOrigin(origins = "*")
public class DebugController {
    
    private static final Logger log = LoggerFactory.getLogger(DebugController.class);
    
    private final ChartConfigService chartConfigService;
    private final DataQueryService dataQueryService;
    
    public DebugController(ChartConfigService chartConfigService, DataQueryService dataQueryService) {
        this.chartConfigService = chartConfigService;
        this.dataQueryService = dataQueryService;
    }
    
    @GetMapping("/config/{chartId}")
    public Map<String, Object> getConfig(@PathVariable String chartId) {
        Map<String, Object> result = new HashMap<>();
        
        ChartConfig config = chartConfigService.getConfigByChartId(chartId);
        if (config != null) {
            result.put("config", config);
            result.put("success", true);
        } else {
            result.put("success", false);
            result.put("message", "配置不存在");
        }
        
        return result;
    }
    
    @PostMapping("/test-query/{chartId}")
    public Map<String, Object> testQuery(@PathVariable String chartId, @RequestBody Map<String, Object> filters) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            ChartConfig config = chartConfigService.getConfigByChartId(chartId);
            if (config == null) {
                result.put("success", false);
                result.put("message", "配置不存在: " + chartId);
                return result;
            }
            
            List<Map<String, Object>> data = dataQueryService.executeQuery(config, filters,0,0);
            
            result.put("success", true);
            result.put("data", data);
            result.put("count", data.size());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            log.error("测试查询失败", e);
        }
        
        return result;
    }
}